package com.platform.core.service.impl;

import com.platform.core.service.LoginService;
import org.springframework.stereotype.Service;

/**
 * 登录-Service实现类
 *
 * @author coder
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Override
    public String login(String username, String password) {
        return null;
    }

    @Override
    public void logout(String token) {

    }

    @Override
    public String refreshToken(String token) {
        return null;
    }

    @Override
    public String getTokenByName(String username) {
        return null;
    }

    /*private final AuthenticationManager authenticationManager;
    private final UserDetailsService userDetailsService;
    private final SysUserService sysUserService;
    private final JwtTokenUtil jwtTokenUtil;
    private final JwtProperties jwtProperties;
    private final DtoMapper dtoMapper;

    @Autowired
    public LoginServiceImpl(AuthenticationManager authenticationManager, @Qualifier("customUserDetailsService") UserDetailsService userDetailsService,
                            SysUserService sysUserService, JwtTokenUtil jwtTokenUtil, JwtProperties jwtProperties, DtoMapper dtoMapper) {
        this.authenticationManager = authenticationManager;
        this.userDetailsService = userDetailsService;
        this.sysUserService = sysUserService;
        this.jwtTokenUtil = jwtTokenUtil;
        this.jwtProperties = jwtProperties;
        this.dtoMapper = dtoMapper;
    }

    @Override
    public String login(String username, String password) {
        if (Strings.isNullOrEmpty(username) || Strings.isNullOrEmpty(password)) {
            throw new RestApiException("用户名或密码不能为空");
        }
        //用户验证
        final Authentication authentication = authenticate(username, password);
        //存储认证信息
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //生成token
        final JwtTokenUtil.JwtUser userDetail = (JwtTokenUtil.JwtUser) authentication.getPrincipal();
        return jwtTokenUtil.generateAccessToken(userDetail);
    }

    @CacheEvict(value = BASE_REDIS_CACHE_PREFIX + "user",
            key = "T(com.platform.core.security.auth.AuthenticationFacade).userCacheKey",
            condition = "T(com.platform.core.security.auth.AuthenticationFacade).userCacheKey != null ")
    @Override
    public void logout(String token) {
        token = token.substring(jwtProperties.getTokenHead().length());
        String userName = jwtTokenUtil.getUsernameFromToken(token);
        jwtTokenUtil.deleteToken(userName);
    }

    private Authentication authenticate(String username, String password) {
        try {
            //该方法会去调用userDetailsService.loadUserByUsername()去验证用户名和密码，如果正确，则存储该用户名密码到“security 的 context中”
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (DisabledException | UsernameNotFoundException | BadCredentialsException e) {
            if (e instanceof BadCredentialsException) {
                throw new RestApiException("用户名或密码错误");
            } else {
                throw new RestApiException(e.getMessage());
            }
        }
    }

    @Override
    public String refreshToken(String oldToken) {
        String token = oldToken;
        String username = jwtTokenUtil.getUsernameFromToken(token);
        CustomUserDetails userDetail = (CustomUserDetails) userDetailsService.loadUserByUsername(username);
        Date date = Date.from(userDetail.getLastPasswordReset().atZone(ZoneId.systemDefault()).toInstant());
        if (jwtTokenUtil.canTokenBeRefreshed(token, date)) {
            token = jwtTokenUtil.refreshToken(token);
            return token;
        }
        return null;
    }

    @Override
    public String getTokenByName(String username) {
        if (Strings.isNullOrEmpty(username)) {
            throw new RestApiException("用户名不能为空");
        }
        UserDetail user = sysUserService.findByUsername(username);
        if (Objects.isNull(user)) {
            throw new RestApiException("用户不存在");
        }
        //用户验证
        final Authentication authentication = authenticate(username, "");
        //存储认证信息
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //获得授权后可得到用户信息(非jwt 方式)
        CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
        //使用jwt生成token 用于权限效验
        JwtTokenUtil.JwtUser jwtUser = dtoMapper.map(userDetails, JwtTokenUtil.JwtUser.class);
        jwtUser.setPwdExpire(DateTimeUtil.toStdLongTimeStr(userDetails.getLastPasswordReset()));
        jwtUser.setAuth(userDetails.getAuthorities()
                .parallelStream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.joining(",")));
        return jwtTokenUtil.generateAccessToken(jwtUser);
    }*/
}
